
import caretDown from '../icon/caret-down.svg'
import caretRight from '../icon/caret-right.svg'

export default function (hiprint) {
  return function (options) {
    const { moduleName, moduleKey, elementList }=  options
    const addElementTypes = function (context) {
      const _elementList = elementList.map(item => {
        item.tid = `${moduleKey}.${item.dictValue}`
        return {
          tid: `${moduleKey}.${item.dictValue}`,
          title: item.dictLabel,
          data: "",
          type: "text",
          options: {
            field: item.dictValue,
            isData:true,// 属于数据字段
          }
        }
      })
      context.removePrintElementTypes(moduleKey);
      context.addPrintElementTypes(moduleKey, [
        new hiprint.PrintElementTypeGroup(moduleName, _elementList)
      ]);
    };
    return {
      addElementTypes: addElementTypes
    };
  };
}

export const custom_dataType = (
  function () {
    function t({ typeList, addCallBack }) {
      this.name = "custom_dataType";
      this.typeList = typeList
      this.addCallBack = (target) => addCallBack(target)
      this.customList = []
    }
    t.prototype.css = function (t, e) {
      if (t && t.length) {
        if (e) return t.css("font-size", e + "pt"), "font-size:" + e + "pt";
        t[0].style.fontSize = "";
      }
      return null;
    }
    // 属性渲染
    t.prototype.createTarget = function () {
      const html = `
        <div class="hiprint-option-item hiprint-option-item-row">
          <div class="hiprint-option-item-label">数据类型</div>
            <div class="hiprint-option-item-field" style="display: flex">
              <!-- 数据格式 -->
              <select class="custom_dataType_item auto-submit" style="margin-right: 5px;">
                <option value="string">字符串</option>
                <option value="number">数字</option>
                <option value="date">日期</option>
                <option value="dict">字典</option>
              </select>
              <!-- 字典 -->
              <select class="custom_dataType_dict auto-submit" style="margin-right: 5px;">
                ${
                  this.typeList.map(item => {
                    return `<option value="${item.dictType}">${item.dictName}</option>`
                  }).join('\n')
                }
                <option value="custom_code">自定义</option>
              </select>
              <div class="custom_add_btn" style="padding: 4px 15px;background: #335EF8;color: #fff">+</div>
            </div>
        </div>
      `
      this.target = $(html)
      this.target.find(".custom_dataType_item").change(() => {
        this.dictShow()
      })
      this.target.find(".custom_add_btn").click(() => {
        this.addCallBack(this)
      })
      return this.target;
    }
    t.prototype.getValue = function () {
      const data = { customList: this.customList }
      const dataType = this.target.find(".custom_dataType_item").val()
      if (dataType) {
        data.dataType = dataType
        if (dataType === 'dict') {
          const dictType = this.target.find(".custom_dataType_dict").val();
          data.dictType = dictType
        } else if (dataType === 'custom') {
          const customType = this.target.find(".custom_dataType_list").val();
          data.customType = customType
        }
      }
      return JSON.stringify(data)
    }
    t.prototype.setValue = function (t) {
      if (t) {
        const { dataType, dictType, customList, customType } = JSON.parse(t)
        dataType && this.target.find(".custom_dataType_item").val(dataType)
        dictType && this.target.find(".custom_dataType_dict").val(dictType)
        setTimeout(() => {
          customType && this.target.find(".custom_dataType_list").val(customType)
        }, 0)
        this.customList = customList || []
      } 
      this.dictShow()
      this.renderCustomList()
    }
    t.prototype.dictShow = function() {
      const dataType = this.target.find(".custom_dataType_item").val()
      this.target.find(".custom_dataType_dict").hide()
      this.target.find(".custom_dataType_list").hide()
      if (dataType === 'dict') {
        this.target.find(".custom_dataType_dict").show()
      } else if (dataType === 'custom') {
        this.target.find(".custom_dataType_list").show()
      }
    }
    t.prototype.dataTypeAdd = function ({ name, code }) {
      this.customList.push({ name, code })
      this.renderCustomList()
      this.submit()
    }
    t.prototype.renderCustomList = function(init=false) {
      const html = this.customList.map(item => {
        return `<option value="${item.code}">${item.name}</option>`
      }).join('\n')
      if (init) {
        return html
      }
      this.target.find(".custom_dataType_list").html(html)
    }
    t.prototype.destroy = function () {
      this.target.remove();
    }
    return t
  }()
)
export const custom_dataSource = (
  function () {
    function t({ treeList }) {
      this.name = "custom_dataSource";
      this.treeList = treeList
      this.selectId = ''
      this.open = false
      this.listDatas = {}

      const init = (list) => {
        list.forEach(item => {
          this.listDatas[item.value] = item
          if (item.children) {
            init(item.children)
          }
        })
      }
      init(treeList)
    }
    t.prototype.css = function (t, e) {
      if (t && t.length) {
        if (e) return t.css("font-size", e + "pt"), "font-size:" + e + "pt";
        t[0].style.fontSize = "";
      }
      return null;
    }
    t.prototype.createTarget = function () {
      this.open = false
      const html = `
        <style>
          .custom_dataSource_select_box {
            padding: 3px;
            z-index: 1;
            border: 1px solid #a9a9a9;
            height: 30px;
          }
          .custom_dataSource_box {
            border: 1px solid #a9a9a9;
            padding: 5px 10px;
            font-size: 14px;
            line-height: 24px;
            left: 0;
            top: 30px;
            width: 100%;
            z-index: 2;
            background: #fff;
            max-height: 400px;
          }
          .custom_dataSource_box2 {
            padding-left: 20px;
          }
          .last-tile, .first-title {
            padding: 0 5px;
          }
          .last-tile:hover {
            background: #335EF8;
            color: #fff;
          }
        </style>
        
        <div class="hiprint-option-item hiprint-option-item-row">
          <div class="hiprint-option-item-label">
            组件数据源
          </div>
          <div class="posr">
            <div class="custom_dataSource_select_box">请选择</div>
            <div class="custom_dataSource_box posa ova" style="display: none">
              ${this.treeList.map(item => {
                return `
                  <div class="flex flex-ac">
                    <img c-id="${item.value}" c-close-id="${item.value}" custom-typ="close" class="tree-icon" style="width: 8px;height: 8px;display: none" src="${caretDown}">
                    <img c-id="${item.value}" c-open-id="${item.value}" custom-typ="open" class="tree-icon" style="width: 8px;height: 8px;" src="${caretRight}">
                    <div class="font-12 first-title">${item.label}</div>
                  </div>
                  <div cb-id="${item.value}" class="custom_dataSource_box2" style="display: none">
                    ${
                      item.children 
                      ? item.children.map(item2 => `
                          <div data-id="${item2.value}" class="custom_dataSource_select_item font-12 last-tile cup">${item2.label}</div>
                        `).join('')
                      : ''
                    }
                  </div>
                `
              }).join('')}
              
            </div>
          </div>
        </div>
      `
      this.target = $(html)
      this.target.find(".custom_dataSource_select_box").click((ev) => {
        ev.stopPropagation()
        this.setOpen()
      })
      this.target.find(".custom_dataSource_box").click((ev) => {
        ev.stopPropagation()
      })
      window.addEventListener('click', () => {
        this.open = false
        this.target.find('.custom_dataSource_box').hide()
      })
      setTimeout(() => {
        const domList = document.querySelectorAll('.tree-icon')
        for (let i = 0; i < domList.length; i++) {
          const dom = domList[i];
          dom.onclick = function(ev) {
            const id = ev.target.getAttribute('c-id')
            const type = ev.target.getAttribute('custom-typ')
            ev.target.style.display = 'none'
            if (type === 'open') {
              document.querySelector(`[c-close-id="${id}"]`).style.display = 'block'
              document.querySelector(`[cb-id="${id}"]`).style.display = 'block'
            } else {
              document.querySelector(`[c-open-id="${id}"]`).style.display = 'block'
              document.querySelector(`[cb-id="${id}"]`).style.display = 'none'
            }
          }
        }

        const selectItem = document.querySelectorAll('.custom_dataSource_select_item')
        for (let i = 0; i < selectItem.length; i++) {
          const dom = selectItem[i];
          dom.onclick = (ev) => {
            this.selectId = ev.target.getAttribute('data-id')
            this.open = false
            this.target.find('.custom_dataSource_box').hide()
            this.submit()
            this.boxTitle()
          }
        }

        this.boxTitle()
      }, 0)
      return this.target;
    }
    t.prototype.boxTitle = function() {
      const row = this.listDatas[this.selectId]
      if (row) {
        this.target.find('.custom_dataSource_select_box').html(row.label)
      } else if (this.selectId) {
        console.log(this.selectId);
        this.target.find('.custom_dataSource_select_box').html(this.selectId)
      }
    }
    t.prototype.setOpen = function () {
      if (!this.target) return
      if (this.open) {
        this.target.find('.custom_dataSource_box').hide()
      } else {
        this.target.find('.custom_dataSource_box').show()
      }
      this.open = !this.open
    }
    t.prototype.getValue = function () {
      return this.selectId
    }
    t.prototype.setValue = function (t) {
      if (t) {
        this.selectId = t
      }
    } 
    t.prototype.destroy = function () {
      this.target.remove();
    } 
    return t
  }()
)
export const custom_dataSource_id = (
  function () {
    function t({ treeList, dataSourceCallBack }) {
      this.name = "custom_dataSource_id"
      this.treeList = treeList
      this.dataSourceCallBack = (target) => dataSourceCallBack(target)
    }
    t.prototype.createTarget = function (t) {
      const html = `
        <div class="hiprint-option-item hiprint-option-item-row">
          <div class="hiprint-option-item-label">
            数据源
          </div>
          <div class="hiprint-option-item-field">
            <select class="auto-submit custom_fields_item">
              <option value="">无</option>
              ${this.treeList.map(item => `<option value="${item.value}">${item.label}</option>`).join('')}
            </select>
          </div>
        </div>
      `
      this.target = $(html)
      this.target.find(".custom_fields_item").change(() => {
        let value =  this.target.find(".custom_fields_item").val()
        setTimeout(()=> this.dataSourceCallBack(),0)
      })
      return this.target;
    } 
    t.prototype.css = function (t, e) {
      if (t && t.length) {
        if (e) return t.css("font-family", e), "font-family:" + e;
        t[0].style.fontFamily = "inherit"; // 从父元素继承字体, 否则模板字体无效
      }
      return null;
    } 
    t.prototype.getValue = function () {
      const dataSourceId = this.target.find(".custom_fields_item").val()
      return dataSourceId || ''
    } 
    t.prototype.setValue = function (t) {
      t && this.target.find(".custom_fields_item").val(t)
    }, 
    t.prototype.destroy = function () {
      this.target.remove();
    }
    return t;
  }()
)
export const custom_field = (
  function () {
    function t() {
      this.name = "field";
    }
    t.prototype.createTarget = function (t, o) {
      this.target = $(this.getDefaultField(t))
      return this.target;
    }
    t.prototype.getValue = function () {
      return (this.isSelect ? this.target.find("select").val() : this.target.find("input").val()) || void 0;
    }
    t.prototype.setValue = function (t) {
      this.isSelect ? t && (this.target.find('option[value="' + t + '"]').length || this.target.find("select").prepend('<option value="' + t + '" >' + t + "</option>"), this.target.find("select").val(t)) : this.target.find("input").val(t);
    }
    t.prototype.destroy = function () {
      this.target.remove();
    }
    t.prototype.getDefaultField = function(t) {
      const getFields = t?.getFields()
      let html = ''
      if (getFields) {
        this.isSelect = true;
        html = `
          <div class="hiprint-option-item hiprint-option-item-row">
            <div class="hiprint-option-item-label">字段名</div>
            <div class="hiprint-option-item-field"> 
              <select class="auto-submit">
                <option value="" >请选择字段</option>
                ${getFields.map(item => `
                  <option value="${item.field}" >${item.text}</option>
                `)}
              </select>
            </div>
          </div>
        `
      } else {
        this.isSelect = false;
        html = `
          <div class="hiprint-option-item hiprint-option-item-row">
            <div class="hiprint-option-item-label">字段名</div>
            <div class="hiprint-option-item-field">
              <input type="text" placeholder="请输入字段名" class="auto-submit">
            </div>
          </div>
        `
      }
      return html
    }
    return t
  }()
)
export const custom_isPrint = (
  function () {
    function t() {
      this.name = "isPrint";
    }
    t.prototype.css = function (t, e) {}
    t.prototype.createTarget = function () {
      this.target = $(`
        <div class="hiprint-option-item hiprint-option-item-row">
          <div class="hiprint-option-item-label">是否打印</div>
          <div class="hiprint-option-item-field">
            <select class="auto-submit">
              <option value="" >默认</option>
              <option value="1" >是</option>
              <option value="2" >否</option>
            </select>
          </div>
        </div>
      `)
      return this.target;
    }
    t.prototype.getValue = function () {
      return this.target.find("select").val();
    }
    t.prototype.setValue = function (t) {
      this.target.find("select").val(t);
    }
    t.prototype.destroy = function () {
      this.target.remove();
    }
    return t;
  }()
)